<?php
namespace Misyuan;
 
 
class Route
{
    /** @var null  模块 */
    private static $module = null;
    /** @var null 控制器 */
    private static $controller = null;
    /** @var null 方法 */
    private static $action = null;
    /** @var  控制器url */
    private static $controllerPath;
    private static  $Request ;
    /**
     * route constructor.
     * @param array $config url
     */
    public function __construct($config = [],$Request)
    {
        $var_parse = explode('/', $config['r']);
        // var_dump($var_parse);
         self::$Request =  $Request;
        if (count($var_parse) == 4){
            self::$module = $var_parse[1];
            self::$controller =  ucwords($var_parse[2]).'Controller';
            self::$action = $var_parse[3];
            self::$controllerPath = APP_ROOT.DIR.self::$module."\controllers".DIR.self::$controller.'';
        }elseif(count($var_parse) == 2||count($var_parse) == 3){
            self::$controller =  ucwords($var_parse[1]).'Controller';
            self::$action = $var_parse[2]?$var_parse[2]:'index';
            self::$controllerPath = APP_ROOT.'\controllers'.DIR.self::$controller.'';
        }
        // var_dump( self::$controllerPath);
        //   echo self::$action."_|";
    }

    /**
     * 执行控制器方法
     * @return null
     */
    public static function run(){
   
        try {
    
         if (class_exists(self::$controllerPath)) {
                  $controller = new self::$controllerPath;
                 $action = self::$action;
        //   var_dump($controller);
        // $controller = new self::$controller;
        if(method_exists($controller, self::$action)){
            return $controller->$action(self::$Request );
        }else{
       
            header("HTTP/1.1 404 Not Found");
        }
    
} else {
        //  echo static::$_publicPath.self::$Request->url();
           return \file_get_contents(public_path().self::$Request->path() );
}
     
        } catch (\Exception $e) {
            // var_dump($e);
        }  
      
    }

    /**
     * 加载类
     */
    public static function register(){
        spl_autoload_register("self::loadClass");
    }

    //自动加载
    public static function loadClass(){
        // if(!file_exists(self::$controllerPath)){
        //     header("HTTP/1.1 404 Not Found");
        // }
        echo self::$controllerPath;;
       
    }
}